const app = getApp()

Page({
  data: {
    products: [],
    totalAmount: 0,
    remark: '',
    shop: null
  },

  onLoad(options) {
    if (options.products) {
      const products = JSON.parse(options.products)
      this.setData({ products })
      this.loadShopInfo(products[0].shopId)
      this.calculateTotal()
    }
  },

  // 加载店铺信息
  async loadShopInfo(shopId) {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('shops').doc(shopId).get()
      this.setData({ shop: data })
    } catch (error) {
      console.error('加载店铺信息失败：', error)
    }
  },

  // 计算总金额
  calculateTotal() {
    let total = 0
    this.data.products.forEach(product => {
      total += product.price * product.quantity
    })
    this.setData({
      totalAmount: total.toFixed(2)
    })
  },

  // 输入备注
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  // 生成订单号
  generateOrderNo() {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
    return `${year}${month}${day}${random}`
  },

  // 提交订单
  async submitOrder() {
    if (!app.globalData.openid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    try {
      wx.showLoading({ title: '提交中...' })
      
      const db = wx.cloud.database()
      const orderData = {
        orderNo: this.generateOrderNo(),
        userId: app.globalData.openid,
        shopId: this.data.shop._id,
        products: this.data.products,
        totalAmount: parseFloat(this.data.totalAmount),
        status: 'pending',
        remark: this.data.remark,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
      
      // 创建订单
      const { _id } = await db.collection('orders').add({
        data: orderData
      })
      
      // 清空购物车中的已购商品
      if (this.data.fromCart) {
        const cart = await db.collection('cart')
          .where({
            userId: app.globalData.openid,
            shopId: this.data.shop._id
          })
          .get()
        
        if (cart.data.length > 0) {
          const cartProducts = cart.data[0].products.filter(p => 
            !this.data.products.find(op => op.id === p.id)
          )
          
          if (cartProducts.length > 0) {
            await db.collection('cart').doc(cart.data[0]._id).update({
              data: {
                products: cartProducts,
                updateTime: db.serverDate()
              }
            })
          } else {
            await db.collection('cart').doc(cart.data[0]._id).remove()
          }
        }
      }
      
      wx.hideLoading()
      wx.showToast({
        title: '下单成功'
      })
      
      // 跳转到订单详情页
      setTimeout(() => {
        wx.redirectTo({
          url: `/pages/order/detail?id=${_id}`
        })
      }, 1500)
    } catch (error) {
      console.error('提交订单失败：', error)
      wx.hideLoading()
      wx.showToast({
        title: '提交失败',
        icon: 'none'
      })
    }
  }
}) 